<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>admin table</title>
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>

<div onclick="openAddGoods()" style="margin-left: 20px;margin-top: 10px">
    <button type="button" class="layui-btn">添加商品</button>
</div>
<div class="layui-form" lay-filter="layuiadmin-app-form-list" style="margin: 10px 20px">

    <div>
        <div class="layui-inline">
            <input class="layui-input" id="keywordGoods" name="keyword" placeholder="请输入商品名" autocomplete="off">
        </div>
        <button class="layui-btn" id="searchGoods" data-type="reload">搜索</button>
    </div>
    <table id="list" lay-filter="goodsList"></table>

</div>
<div id="openSpecificationsList" class="layui-row" hidden>
    <div class="layui-form" lay-filter="layuiadmin-app-form-list" style="margin: 10px 20px">
        <div>
            <div class="layui-inline">
                <input class="layui-input" id="keywordSpe" name="keyword" placeholder="请输入规格名" autocomplete="off">
            </div>
            <button class="layui-btn" id="searchSpe" data-type="reload">搜索</button>
        </div>
        <table id="specifications" lay-filter="specificationsList"></table>
        <div style="text-align: center;">
            <button id="bind" type="button" class="layui-btn">立即绑定</button>
        </div>
    </div>
</div>
<div id="openAdd" class="layui-row" hidden>
    <div style="margin-left: 10%;margin-top: 5px;width: 80%">
        <form lay-filter="addGoods" class="layui-form" action="">
            <input name="id" type="number" hidden/>
            <div class="layui-form-item">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入商品名称"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品副标题</label>
                <div class="layui-input-block">
                    <input type="text" name="subtitle" required lay-verify="required" placeholder="请输入商品副标题"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品封面</label>
                <div class="layui-input-block" style="display: flex">
                    <input id="fileIcon" type="text" lay-verify="fileIcon" autocomplete="off" class="layui-input"
                           disabled>
                    <button type="button" class="layui-btn" id="uploadIcon">
                        上传封面
                    </button>
                </div>
                <input name="icon" hidden/>
                <div class="layui-collapse" style="margin-top: 5px">
                    <div class="layui-colla-item">
                        <h2 class="layui-colla-title">
                            展开封面
                        </h2>
                        <div class="layui-colla-content" id="colla_icon" style="">
                        </div>
                    </div>
                </div>
            </div>
            <!--            <div class="layui-form-item">-->
            <!--                <label class="layui-form-label">商品图册</label>-->
            <!--                <div class="layui-input-block" style="display: flex">-->
            <!--                    <input id="fileMedia" type="text" lay-verify="fileMedia" autocomplete="off" class="layui-input"-->
            <!--                           disabled>-->
            <!--                    <button type="button" class="layui-btn" id="uploadMedia">-->
            <!--                        <i class="layui-icon">&#xe67c;</i>上传图册-->
            <!--                    </button>-->
            <!--                </div>-->

            <!--                <input name="media" hidden/>-->
            <!--                <div class="layui-collapse" style="margin-top: 5px">-->
            <!--                    <div class="layui-colla-item">-->
            <!--                        <h2 class="layui-colla-title">-->
            <!--                            展开图册-->
            <!--                        </h2>-->
            <!--                        <div class="layui-colla-content" id="colla_media" style="">-->
            <!--                        </div>-->
            <!--                    </div>-->
            <!--                </div>-->
            <!--            </div>-->
            <div class="layui-form-item">
                <label class="layui-form-label">销售渠道</label>
                <div class="layui-input-block">
                    <input type="radio" name="item" value="1" title="线上" checked>
                    <input type="radio" name="item" value="2" title="线下">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">规格</label>
                <div class="layui-input-block">
                    <input type="radio" name="isSpec" value="1" title="开启" checked>
                    <input type="radio" name="isSpec" value="2" title="关闭">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-block">
                    <input type="number" name="price" required lay-verify="required" placeholder="请输入价格"
                           onkeyup="value=value.replace(/^(0+)|[^\d.]+/g,'')" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">批发价格</label>
                <div class="layui-input-block">
                    <input type="number" name="wholesale_price" lay-verify="" placeholder="请输入批发价格"
                           step="0.01" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">库存</label>
                <div class="layui-input-block">
                    <input type="number" name="stock" lay-verify="" placeholder="请输入库存"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">详细介绍</label>
                <div class="layui-input-block">
                    <textarea name="body" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">排序</label>
                <div class="layui-input-block">
                    <input type="number" name="sort" lay-verify="" placeholder="请输入库存"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">推荐</label>
                <div class="layui-input-block">
                    <input type="radio" name="is_recommend" value="1" title="是" checked>
                    <input type="radio" name="is_recommend" value="2" title="否">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">显示</label>
                <div class="layui-input-block">
                    <input type="radio" name="display" value="1" title="显示" checked>
                    <input type="radio" name="display" value="2" title="隐藏">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品单位id</label>
                <div class="layui-input-block">
                    <input type="number" name="unit" placeholder="请输入商品单位id"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">外送重量/数量</label>
                <div class="layui-input-block">
                    <input type="number" name="unit_weight" lay-verify="" placeholder="请输入外送重量/数量"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">详情</label>
                <div class="layui-input-block">
                    <textarea name="details" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品产地</label>
                <div class="layui-input-block">
                    <input type="text" name="place_of_origin" lay-verify="" placeholder="请输入产地"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="1" title="正常" checked>
                    <input type="radio" name="status" value="2" title="下架">
                    <input type="radio" name="status" value="3" title="风险下架">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">起购数量</label>
                <div class="layui-input-block">
                    <input type="number" name="min_num" lay-verify="" placeholder="请输入起购数量"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">限购数量</label>
                <div class="layui-input-block">
                    <input type="number" name="max_num" lay-verify="" placeholder="请输入限购数量"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button id="addGoods" type="button" class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>

</div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

<script src="../layui/layui.js"></script>
<script>
    layui.use('table', function () {
        var table = layui.table;

        //第一个实例
        table.render({
            elem: '#list',
            // height: 312,
            url: 'goodsList?needData=1', //数据接口//
            request: {
                limitName: 'size' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                if (res.code == 200)
                    res.code = 0
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            },
            page: true,//开启分页
            cols: [[ //表头
                {field: 'id', title: 'ID', width: '100', sort: true},
                {field: 'name', title: '商品名称', width: '100'},
                {field: 'subtitle', title: '商品副标题', width: '100'},
                {
                    field: 'item', title: '销售渠道', width: '100', templet: function (d) {
                        show = '异常'
                        if (d.item == 1)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="offline">线上</a>'
                        if (d.item == 2)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="online">线下</a>'
                        return show
                    }
                },
                {
                    field: 'isSpec', title: '规格', width: '150', templet: function (d) {
                        show = '异常'
                        if (d.isSpec == 1){
                            show = '<a class="layui-btn layui-btn-xs" lay-event="close">开启</a>'+
                                '<a class="layui-btn layui-btn-xs" lay-event="bindSpecifications">规格</a>'
                        }
                        if (d.isSpec == 2)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="open">关闭</a>'
                        return show
                    }
                },
                {field: 'price', title: '价格', width: '100'},
                {field: 'salesNum', title: '销量', width: '100'},
                {field: 'stock', title: '库存', width: '100'},
                {
                    field: 'is_recommend', title: '推荐商品', width: '100', templet: function (d) {
                        show = '异常'
                        if (d.is_recommend == 1)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="notRecommend">推荐</a>'
                        if (d.is_recommend == 2)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="recommend">不推荐</a>'
                        return show
                    }
                },
                {
                    field: 'display', title: '展示', width: '100', templet: function (d) {
                        show = '异常'
                        if (d.display == 1)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="hide">展示</a>'
                        if (d.display == 2)
                            show = '<a class="layui-btn layui-btn-xs" lay-event="show">隐藏</a>'
                        return show
                    }
                },
                {field: 'place_of_origin', width: '100', title: '产地'},
                {
                    field: 'status', title: '展示', width: '100', unresize: true, templet: function (d) {
                        var status = '异常'
                        if (d.status == 1)
                            status = '正常'
                        if (d.status == 2)
                            status = '下架'
                        if (d.status == 3)
                            status = '风险下架'
                        return status;
                    }
                },
                {field: 'min_num', title: '起售数量', width: '100'},
                {field: 'max_num', title: '限购数量', width: '100'},
                {field: 'create_time', title: '创建时间', width: '200'},
                {field: 'update_time', title: '更新时间', width: '200'},
                {
                    fixed: 'right', title: '操作', width: '150', templet: function (d) {

                        show = '    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>\n' +
                            '    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>'
                        return show
                    }
                }
            ]],
            text: {
                none: '暂无数据' //默认：无数据。
            },
            defaultToolbar: ['filter'],
        })
        $('#searchGoods').click(function () {
            var keyword = $('#keywordGoods').val()
            table.reload('list', {
                url: 'goodsList?needData=1&keyword=' + keyword, //数据接口//
            });
        })
        table.on('tool(goodsList)', function (obj, table) {
            // var data = obj.data; //获得当前行数据
            // if (layEvent == 'edit') {
            //     window.location = 'editPsw.html?aid=' + data.admin_id
            // }
            switch (obj.event) {
                case 'online':
                    tableSingleAttributeUpdate(obj, 'item', 1)
                    break;
                case 'offline':
                    tableSingleAttributeUpdate(obj, 'item', 2)
                    break;
                case 'open':
                    tableSingleAttributeUpdate(obj, 'isSpec', 1)
                    break;
                case'close':
                    tableSingleAttributeUpdate(obj, 'isSpec', 2)
                    break;
                case 'recommend':
                    tableSingleAttributeUpdate(obj, 'is_recommend', 1)
                    break;
                case'notRecommend':
                    tableSingleAttributeUpdate(obj, 'is_recommend', 2)
                    break;
                case 'show':
                    tableSingleAttributeUpdate(obj, 'display', 1)
                    break;
                case'hide':
                    tableSingleAttributeUpdate(obj, 'display', 2)
                    break;
                case'bindSpecifications':
                    openSpecificationsList(obj)
                    break;
                case 'edit':
                    openEditGoods(obj.data)
                    break;
                case 'del':
                    layer.confirm('确定删除该商品？', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        //向服务端发送删除指令
                        obj.data['deleted'] = 1
                        edit(obj.data)
                    });
                    break;

            }
        });

    });


    function tableSingleAttributeUpdate(obj, field, value) {
        obj.data[field] = value
        edit(obj.data, function (res) {
            if (res.code != 200) {
                layer.msg(res.error)
            } else {
                layer.msg('修改成功')
                var f = {}
                f[field] = value
                obj.update(f);
            }
        })
    }

    function edit(data, callback) {
        $.ajax({
            url: 'editGoods',
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function (res) {
                if (callback != 'undefined') {
                    callback(res)
                } else {
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('修改成功')
                    }
                }
            },
        });
    }

    function openAddGoods() {
        layer.open({
            type: 1,
            content: $('#openAdd'),
            area: ["500px", "500px"],
            title: '添加商品',
            anim: 1
        });
        $('button[type=reset]').click()
    }

    function openSpecificationsList(obj) {
        $('#bind').on('click', function () {
            var data = {}
            data['goodsId'] = obj.data['id']
            data['add'] = []
            data['del'] = []
            $('input[name=speId]').each(function () {
                var status = $(this).prop('checked')
                var v = $(this).val()
                if (status == true) {
                    var rel = {}
                    rel['spe_id'] = v
                    rel['goods_id'] = data['goodsId']
                    data['add'].push(rel)
                } else {
                    data['del'].push(v)
                }
            })
            console.log(data)
            $.ajax({
                url: 'editSpecificationsRelationship',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function () {
                    location.reload()
                }
            })
        })
        $.ajax({
            url: 'specificationsRelationship?goodsId=' + obj.data['id'],
            type: 'GET',
            success: function (relat) {
                var arr = relat.data
                layer.open({
                    type: 1,
                    content: $('#openSpecificationsList'),
                    area: ["500px", "400px"],
                    title: '规格信息',
                    anim: 1,
                    success: function () {
                        layui.use('table', function () {
                            var table = layui.table;
                            //第一个实例
                            table.render({
                                id: 'specificationsList',
                                elem: '#specifications',
                                height: 300,
                                url: 'specificationsList?needData=1&status=1', //数据接口//
                                request: {
                                    limitName: 'size' //每页数据量的参数名，默认：limit
                                },
                                parseData: function (res) { //res 即为原始返回的数据
                                    if (res.code == 200)
                                        res.code = 0
                                    return {
                                        "code": res.code, //解析接口状态
                                        "msg": res.message, //解析提示文本
                                        "count": res.data.total, //解析数据长度
                                        "data": res.data.data //解析数据列表
                                    };
                                },
                                page: true,//开启/分页
                                cols: [[ //表头
                                    {
                                        field: 'id', title: 'ID', width: '100', sort: true, templet: function (d) {
                                            var checked = ''
                                            if ($.inArray(d.id, arr) >= 0)
                                                checked = 'checked'
                                            return '<input value="' + d.id + '" type="checkbox" name="speId" lay-skin="primary" ' + checked + '><span style="margin-left: 5px">' + d.id + '</span>'
                                        }
                                    },
                                    {field: 'name', title: '规格名称', width: '100'},
                                    {field: 'spec_price', title: '规格价格', width: '100'},
                                    {field: 'sort', title: '排序', width: '100'},
                                    {field: 'create_time', title: '创建时间', width: '200'},
                                ]],
                            })
                            $('#searchSpe').click(function () {
                                var keyword = $('#keywordSpe').val()
                                table.reload('specificationsList', {
                                    url: 'specificationsList?needData=1&status=1&keyword=' + keyword, //数据接口//
                                });
                            })

                        })
                    }
                })
            }
        })
    }


    function openEditGoods(data) {
        layer.open({
            type: 1,
            content: $('#openAdd'),
            area: ["500px", "500px"],
            title: '编辑商品信息',
            anim: 1,
            success: function () {
                form = layui.form
                form.val('addGoods', data)
                $('#fileIcon').val(data['icon']); //展示文件名
                $('#colla_icon').find('img').remove();
                $('#colla_icon').append('<a href="#" onclick="openImg();"><img id="showImg" src="' + data['icon'] + '" width="370px"></a>');
            }
        });
    }

    //Demo
    layui.use('form', function () {
        var form = layui.form;

        $('#addGoods').on('click', function () {
            var formData = form.val('addGoods')
            if (formData['id'] <= 0)
                delete formData['id']
            else {
                delete formData['file']
                edit(formData, function (res) {
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('修改成功')
                        location.reload()
                    }
                })
                return
            }
            $.ajax({
                url: 'addGoods',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (res) {
                    console.log(res)
                    if (res.code != 200) {
                        layer.msg(res.error)
                    } else {
                        layer.msg('添加成功')
                        location.reload();
                    }
                }, error: function (res) {
                    console.log(res)
                    layer.msg()
                }
            })
        })
    });
    layui.use('upload', function () {
        var upload = layui.upload;

        //执行实例
        upload.render({
            elem: '#uploadIcon' //绑定元素
            , url: 'uploadImg' //上传接口
            , choose: function (obj) {
                //预读本地文件
                obj.preview(function (index, file, result) {
                    $('#fileIcon').val(file.name); //展示文件名
                    $('#colla_icon').find('img').remove();
                    $('#colla_icon').append('<a href="#" onclick="openImg();"><img id="showImg" src="' + result + '" width="370px"></a>');
                })
                obj.pushFile()
            }
            , done: function (res) {
                //上传完毕回调
                $('input[name=icon]').val(res.data.url)
                layer.msg('上传成功')
            }
        });
        // upload.render({
        //     elem: '#uploadMedia'
        //     , url: '/api/upload/'
        //     , multiple: true
        //     , auto: false //不自动上传
        //     , bindAction: '#upload_icon' //上传绑定到隐藏按钮
        //     , choose: function (obj) {
        //         //预读本地文件
        //         obj.preview(function (index, file, result) {
        //             $('#fileMedia').val(file.name); //展示文件名
        //             $('#colla_media').find('img').remove();
        //             $('#colla_media').append('<a href="#" onclick="openImg();"><img id="showImg" src="' + result + '" width="370px"></a>');
        //         })
        //     }
        //     , allDone: function (obj) { //当文件全部被提交后，才触发
        //         console.log(obj.total); //得到总文件数
        //         console.log(obj.successful); //请求成功的文件数
        //         console.log(obj.aborted); //请求失败的文件数
        //     }
        //     , done: function (res, index, upload) { //每个文件提交一次触发一次。详见“请求成功的回调”
        //
        //     }
        // });
    });

    /*查看大图*/
    function openImg() {
        var idBar = '#showImg';
        var src = $(idBar)[0].src;
        var width = $(idBar).width();
        var height = $(idBar).height();
        var scaleWH = width / height;
        var bigH = 550;
        var bigW = scaleWH * bigH;
        if (bigW > 1000) {
            bigW = 1000;
            bigH = bigW / scaleWH;
        } // 放大预览图片
        parent.layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            shadeClose: true,
            area: [bigW + 'px', bigH + 'px'], //宽高
            content: '<img width="' + bigW + '" src="' + src + '" />'
        });
    }

</script>
</body>
</html>
